<?php
class Admin_Model_Trip extends TBB_Db_Table_Abstract
{
	/**
	 * Model name
	 * @var string
	 */
	protected $_name = 'trip';
	
	/**
	 * Primary column
	 * @var string
	 */
	protected $_primary = 'trip_id';
	
	/**
	 * Create multiple trips. We can call it scheduling the bus board. 
	 * @param int $routeID
	 * @param int $tripCount
	 * @param int $dayCount
	 * @param string $startDate
	 * @param array $tripLines
	 */
	public function createMultipleTrips($routeID, $tripCount, $dayCount, $startDate, $tripLines = array())
	{
		if(empty($tripLines) || (count($tripLines) != $tripCount))
			throw new Exception('Something wrong');
			
		$db = Zend_Db_Table::getDefaultAdapter();
		$db->beginTransaction();		
		try {
			for($i = 0; $i < $dayCount; ++$i) {				
				foreach($tripLines as $tripLine) {
					$departureDatetimeObj = new Zend_Date(TBB_Utility_Date::formatDateTime($tripLine['departureTime'], 'dd-MM-y HH:mm:ss', 'y-MM-dd HH:mm:ss'));
					$departureDatetimeObj->addDay($i);			
					
					$arrivalDatetimeObj = new Zend_Date(TBB_Utility_Date::formatDateTime($tripLine['arrivalTime'], 'dd-MM-y HH:mm:ss', 'y-MM-dd HH:mm:ss'));
					$arrivalDatetimeObj->addDay($i);										
					
					$tripRow = $this->createRow();
					$tripRow->route_id = $routeID;
					$tripRow->bus_id = $tripLine['bus'];
					$tripRow->departure_time = $departureDatetimeObj->toString('y-MM-dd HH:mm:ss');
					$tripRow->arrival_time = $arrivalDatetimeObj->toString('y-MM-dd HH:mm:ss');;
					$tripRow->fare = $tripLine['fare'];
					$tripRow->expired = 0;
					$tripRow->save();			
				}
			}
			$db->commit();				
		} catch(Exception $e) {
			
			$db->rollBack();
			throw new $e;			
		}		
	}
		
	/**
	 * Get trip paginator adapter
	 * @param string $filtingField
	 * @param string $filtingCriteria
	 * @param string $sortingField
	 * @return Zend_Paginator_Adapter_DbSelect|Zend_Paginator_Adapter_DbTableSelect
	 */
	public function getTripPaginatorAdapter($filtingField, $filtingCriteria, $sortingField)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$select = $db->select()->from(array('t' => 'trip'), 
									  array('t.trip_id',
											't.departure_time',
											't.arrival_time',
											'fare'))
								->joinInner(array('r' => 'route'),
											't.route_id = r.route_id',
											array('r.from_city',
												  'r.to_city'));
		if(!empty($filtingField)) {
			// switch filting field
			switch($filtingField) {
				case 'departure_time':
				case 'arrival_time':
					if(!empty($filtingCriteria)) {
						$dateFormat = new Zend_Date($filtingCriteria, 'dd-MM-y HH:mm:ss');
						$filtingCriteria = $dateFormat->toString('y-MM-dd HH:mm:ss');
					}
					break;
				case 'from_city':
				case 'to_city':
					$db = Zend_Db_Table::getDefaultAdapter();
					$select = $db->select()->from(array('t' => 'trip'), 
												  array('t.trip_id',
												  		't.departure_time',
												  		't.arrival_time',
												  		'fare'))
											 ->joinInner(array('r' => 'route'),
											 			 't.route_id = r.route_id',
											 			 array('r.from_city',
											 			 	   'r.to_city'));	
					break;
				default:
					break;
			}			
			// add filting criteria
			$select->where($filtingField . ' = ?', $filtingCriteria);			
		}
		
		// add sorting criteria
		if(!empty($sortingField)) {
			$select->order($sortingField);
		}
		$adapter = new Zend_Paginator_Adapter_DbSelect($select);
		
		return $adapter;
	}

	/**
	 * Create trip
	 * @param int $routeID
	 * @param int $busID
	 * @param string $departureTime
	 * @param string $arrivalTime
	 * @param int fare
	 * @param int $expired
	 * @return mixed
	 */	
	public function createTrip($routeID, $busID, $departureTime, $arrivalTime, $fare, $expired = 0)
	{
		$tripRow = $this->createRow();
		if($tripRow) {		
			$tripRow->route_id = $routeID;	
			$tripRow->bus_id = $busID;
			$tripRow->departure_time = $departureTime;
			$tripRow->arrival_time = $arrivalTime;
			$tripRow->fare = $fare;
			$tripRow->expired = $expired;
			try {
				return $tripRow->save();
			}catch(Exception $e) {
				throw new $e;		
			}
		}
		throw new Exception('Could not create trip. Trip not found.');
	}	
	
	/**
	 * Update trip
	 * @param int $id
	 * @param int $routeID
	 * @param int $busID
	 * @param string $departureTime
	 * @param string $arrivalTime
	 * @param int fare
	 * @param int $expired
	 * @return mixed
	 */	
	public function updateTrip($id, $routeID, $busID, $departureTime, $arrivalTime, $fare, $expired = 0)
	{		
		$tripRow = $this->find($id)->current();
		if($tripRow) {
			$tripRow->route_id = $routeID;
			$tripRow->bus_id = $busID;
			$tripRow->departure_time = $departureTime;
			$tripRow->arrival_time = $arrivalTime;
			$tripRow->fare = $fare;
			$tripRow->expired = $expired;
			try {			
				return $tripRow->save();
			} catch (Exception $e) {
				throw $e;
			}			
		}
		throw new Exception('Could not update trip. Trip not found.');		
	}
	
	/**
	 * Delete trip
	 * @param $id
	 * @return int
	 */
	public function deleteTrip($id)
	{
		$tripRow = $this->find($id)->current();
		if($tripRow) {
			try {
				return $tripRow->delete();
			} catch(Exception $e) {
				throw $e;
			}
		}
		throw new Exception('Could not delete trip.');
	}	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//////////// (deprecated) ///////////////////
//	public function createMultipleTrips($routeID, $tripCount, $dayCount, $startDate, $tripLines = array())
//	{
//		if(count($tripLines) != $tripCount)
//			throw new Exception('Something wrong');
//			
//		// WAY 2
//		/////////////////// WHY CAN'T? //////////////
//		$params = array();		
//		$sql = 'INSERT INTO trip (route_id, bus_id, departure_time, arrival_time, fare, expired) VALUES ';
//		for($i = 1; $i <= $dayCount; ++$i) {
//			$tripLineCount = count($tripLines); $j = 1;
//			foreach($tripLines as $tripLine) {
//				$sql .= '(?, ?, ?, ?, ?, ?)';
//
//				$departureTime = TBB_Utility_Date::formatDate($startDate, 'dd-MM-y', 'y-MM-dd') . ' ' . $tripLine['departureTime'];
//				$arrivalTime = TBB_Utility_Date::formatDate($startDate, 'dd-MM-y', 'y-MM-dd') . ' ' . $tripLine['departureTime'];
//				
//				// push param to params array
//				array_push($params, $routeID, $tripLine['bus'], $departureTime, $arrivalTime, $tripLine['fare'], 0);				
//								
//				if($j <= $tripLineCount && ($i * $j) < $tripLineCount * $dayCount) {
//					$sql .= ', ';
//				} else if($i * $j == $tripLineCount * $dayCount) {
//					$sql .= ';';
//				}
//				++$j;
//			}
//			
//			// increment a day
//			$date = new Zend_Date($startDate);
//			$startDate = $date->addDay(1);
//		}	
//		echo $sql;
//		echo '<pre>';
//		print_r($params);
//		echo '</pre>'; exit();		
//		$r = 1;
//		$db = Zend_Db_Table::getDefaultAdapter();
//		$stmt = $db->query($sql, $params);
//		$r = $stmt->execute();
//		return $r;
//	}
}